<template>
    <div class="app-container bg-grey">
      <el-form :model="queryP" ref="queryP" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="门店" prop="deptName">
        <el-cascader 
          v-model="queryP.metadata.deptId"
          :options="enabledDeptOptions" 
          :props="cascaderProps"
          :show-all-levels="false"
          clearable
          placeholder="请选择归属部门"
          @change="handleDeptChange"
          @blur="handleCascaderBlur"
          @visible-change="handleCascaderVisibleChange"
          ref="cascaderRef"
        ></el-cascader>
      </el-form-item>

      <el-form-item label="顾客" prop="name">
        <el-select v-model="queryP.metadata.openId" placeholder="请选择顾客" filterable clearable>
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name + ' - ' + item.nickName"
            :value="item.openId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

      <el-table v-loading="loading" :data="threadList" @selection-change="handleSelectionChange" stripe>
        <el-table-column label="门店名称" align="center" prop="deptName">
          <template slot-scope="scope">
            {{ scope.row.deptName }}
          </template>
        </el-table-column>
        <el-table-column label="顾客名称" align="center" prop="name">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="微信昵称" align="center" prop="nickName">
          <template slot-scope="scope">
            {{ scope.row.nickName }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="关联设备" align="center" prop="metadata">
          <template slot-scope="scope">
            {{ scope.row.metadata.uuid }}
          </template>
        </el-table-column>
        <el-table-column label="线程ID" align="center" prop="thread_id" /> -->
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="threadStatus" :value="scope.row.status"/>
          </template>
        </el-table-column>
        
        <el-table-column label="创建时间" align="center" prop="created_at" width="260">
          <template slot-scope="scope">
            {{ formatTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-chat-round"
              @click="handleUpdate(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="bg-grey page-posi-div" v-show="total>0">
        <div class="bg-fff bor-r-10 p10 pb20">
          <pagination
          :total="total"
          :page.sync="queryP.pageNum"
          :limit.sync="queryP.limit"
          @pagination="getList"
          />
        </div>
      </div>
  
      <el-drawer v-if="open"
        :title="title"
        direction="ltr"
        :visible.sync="open"
        :before-close="cancel" 
        size="80%"
        :modal-append-to-body="false"
        :append-to-body="true">
        <div class="p20">

          <el-descriptions title="对话信息" direction="vertical" :column="2" border>
            <el-descriptions-item label="对话标题" :span="2" v-if="form.metadata.ques">{{ form.metadata.ques }}</el-descriptions-item>
            <!-- <el-descriptions-item label="关联数据">{{ form.metadata.key }}</el-descriptions-item>
            <el-descriptions-item label="对话设备" >{{ form.metadata.uuid }}</el-descriptions-item> -->
            <el-descriptions-item label="开始时间">{{ formatTime(form.created_at) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatTime(form.updated_at) }}</el-descriptions-item>
          </el-descriptions>
          <el-divider>对话记录</el-divider>
          <div style="height: calc(100vh - 460px);border-radius: 15px;background: rgba(243,243,243,0.7);overflow-y: auto;
          box-shadow: inset  0 0 5px rgba(0,0,0,0.05);padding:20px;border:1px solid rgba(0,0,0,0.05);">
            <div class="message-item" :class="message.type" v-for="message in form.values.messages">
              <div class="message-bubble">
                <div class="message-text" v-html="upContent(message.content)"></div>
              </div>
            </div>
          </div>

        </div>

      </el-drawer>
     
    </div>
  </template>
  
  <script>
  import langC from "@/api/wenda/langChain";
  import markdown from '@/utils/wenda/markdown.js'; // 引入定义样式后的markdown
  import { listCustomer, getCustomerByOpenId } from "@/api/demo/customer";
  import { deptTreeSelect } from "@/api/system/user";

  export default {
    name: "Post",
    data() {
      return {
        threadStatus:[{value:'idle',label:"空闲",icon:"icon-kongxian",raw:{listClass:'primary'}},{value:'busy',label:"忙碌",icon:"icon-mangluxian",raw:{listClass:'warning'}},{value:'interrupted',label:"中断",icon:"icon-caozuozhongduan",raw:{listClass:'info'}},{value:'error',label:"错误",icon:"icon-cuowu",raw:{listClass:'error'}}],
        threadType:[{value:'user',label:"用户",icon:"icon-yonghu",raw:{listClass:'primary'}},{value:'links',label:"联动",icon:"icon-a-daping",raw:{listClass:'warning'}}],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        names:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 岗位表格数据
        threadList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryP: {
            pageNum:1,
            offset: 0,
            limit: 10,
            status: "idle",
            metadata: {
              type:"user",
              deptId: this.$store.state.user.deptId
            },
        },
        // 表单参数
        form: {},
        isDis :false,
        // 所有部门树选项
        deptOptions: undefined,
        // 过滤掉已禁用部门树选项
        enabledDeptOptions: undefined,
        // 级联选择器配置
        cascaderProps: {
          value: 'id',
          label: 'label',
          children: 'children',
          checkStrictly: true, // 设置为false只能选最后一级，保持级联选择器的正常行为
          emitPath: false // 设置为false只返回最后一级的值
        },
        // 级联选择器引用
        cascaderRef: null,
        customerList:[],
      };
    },
    created() {
      this.getList();
      this.getDeptTree();
      this.getCustomerList(this.$store.state.user.deptId);
    },
    mounted() {
      this.cascaderRef = this.$refs.cascaderRef;
    },
    methods: {
      getCustomerList(deptId) {
        listCustomer({pageNum:1,limit:1000,deptId: deptId}).then(response => {
          this.customerList = response.rows;
        });
      },
      /** 查询部门下拉树结构 */
      getDeptTree() {
        return new Promise((resolve) => {
          deptTreeSelect().then(response => {
            this.deptOptions = response.data;
            this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
            resolve();
          }).catch(() => {
            this.deptOptions = [];
            this.enabledDeptOptions = [];
            resolve();
          });
        });
      },
      
      // 过滤禁用的部门
      filterDisabledDept(deptList) {
        return deptList.filter(dept => {
          if (dept.disabled) {
            return false;
          }
          if (dept.children && dept.children.length) {
            dept.children = this.filterDisabledDept(dept.children);
          }
          return true;
        });
      },
      
      // 部门选择变化处理
      handleDeptChange(value) {
        // 由于设置了 emitPath: false，value 直接就是最后一级的部门ID
        this.queryP.metadata = {
          type:"user",
          deptId: value
        }
        // 延迟执行查询，确保级联选择器完全关闭
        setTimeout(() => {
          this.handleQuery();
        }, 100);
      },
      
      // 处理级联选择器失去焦点
      handleCascaderBlur() {
        // 强制移除任何可能的焦点
        const activeElement = document.activeElement;
        if (activeElement && activeElement.blur) {
          activeElement.blur();
        }
      },
      
      // 处理级联选择器显示状态变化
      handleCascaderVisibleChange(visible) {
        if (!visible) {
          // 级联选择器关闭时，确保移除焦点
          setTimeout(() => {
            this.handleCascaderBlur();
          }, 100);
        }
      },
      
      // 格式化时间
      formatTime(timeString) {
        if (!timeString) return '';
        
        try {
          const date = new Date(timeString);
          // 检查日期是否有效
          if (isNaN(date.getTime())) {
            return timeString;
          }
          
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        } catch (error) {
          console.error('时间格式化错误:', error);
          return timeString;
        }
      },
      
      // 格式化返回内容
      upContent(text) {
        if (text) {
          return markdown.returnContent(text)
        }
      },
      
      upQuery(key,val,isMeta=false){
        if(isMeta){
          this.queryP.metadata[key] = val
        }else{
          this.queryP[key] = val
        }
        this.getList();
      },
      
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryP.pageNum = 1;
        this.getCustomerList(this.queryP.metadata.deptId);
        this.getList();
      },
      
      /** 查询岗位列表 */
      async getList() {
        this.loading = true;
        
        try {
          // 计算偏移量
          this.queryP.offset = (this.queryP.pageNum - 1) * this.queryP.limit;
          
          // 获取线程列表
          const threadRes = await langC.threadList(this.queryP);
          
          // 并行获取所有顾客信息
          const customerPromises = threadRes.map(item => 
            getCustomerByOpenId({
              openId: item.metadata.openId, 
              deptId: item.metadata.deptId
            }).then(customerRes => {
              // 使用 Vue.set 或直接赋值确保响应式更新
              this.$set(item, 'deptName', customerRes.data.deptName || '未知');
              this.$set(item, 'name', customerRes.data.name || '未知');
              this.$set(item, 'nickName', customerRes.data.nickName || '未知');
              return item;
            }).catch(error => {
              console.error('获取顾客信息失败:', error);
              this.$set(item, 'deptName', '未知');
              this.$set(item, 'name', '未知');
              this.$set(item, 'nickName', '未知');
              return item;
            })
          );
          
          // 等待所有顾客信息查询完成
          await Promise.all(customerPromises);
          
          // 设置响应式数据
          this.threadList = threadRes;
          
        } catch (error) {
          console.error('获取线程列表失败:', error);
          this.threadList = [];
        } finally {
          this.loading = false;
        }
        
        // 获取总数（单独处理，不阻塞主流程）
        this.getTotalCount();
      },

      /** 获取总数 */
      getTotalCount() {
        const q = {
          ...this.queryP,
          limit: 999,
          offset: 0,
          metadata: {
            ...this.queryP.metadata
          }
        };
        
        langC.threadList(q).then(res => {
          this.total = res.length;
        }).catch(error => {
          console.error('获取总数失败:', error);
          this.total = 0;
        });
      },
      
      // 取消按钮
      cancel() {
        // 在关闭抽屉前移除焦点
        const activeElement = document.activeElement;
        if (activeElement && activeElement.blur) {
          activeElement.blur();
        }
        
        this.open = false;
        this.isDis = false;
        this.reset();
      },
      
      // 表单重置
      reset() {
        this.form = {};
        this.isDis = false;
        this.resetForm("form");
      },
      
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.names = selection.map(item => item.name)
        this.ids = selection.map(item => item.thread_id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.isDis = false;
        this.title = "添加线程";
      },
      
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.thread_id || this.thread_id;
        
        // 确保没有元素保持焦点
        const activeElement = document.activeElement;
        if (activeElement && activeElement.blur) {
          activeElement.blur();
        }
        
        langC.threadGet(id).then(res => {
          res.configStr = JSON.stringify(res.config)
          res.metadataStr = JSON.stringify(res.metadata)
          res.valuesStr = JSON.stringify(res.values)
          this.form = res;
          if (this.form.values && this.form.values.messages && this.form.values.messages.length > 2) {
            this.form.values.messages = this.form.values.messages.slice(2);
          }else{
            this.form.values = {messages:[]}
          }
          console.log("修改按钮操作", this.form)
          this.open = true;
          this.title = res.metadata.ques
        });
      },

      /** 删除按钮操作 */
      async handleDelete(row) {
        console.log(row)
        const id = row.thread_id
        console.log(this.ids)
        const names = this.ids.length ? '是否确认删除' + this.ids.length + '个数据项？' : '是否确认删除标题为"' + row.metadata.ques + '"的数据项？'

        this.$modal.confirm(names).then(() => {
            if(this.ids.length){
                for (let i = 0; i < this.ids.length; i++) {
                    console.log(this.ids[i])
                    langC.threadDelete(this.ids[i]);
                }
                return true
            }else{
                langC.threadDelete(id);
            }
        }).then(() => {
            this.$modal.msgSuccess("删除成功");
            setTimeout(() => {
                this.getList();
            }, 1000);
        }).catch(() => {});
      },
    }
  };
  </script>
  
<style scoped>
/* 对话框 */
.message-item {
  margin-bottom: 5px;
}

.message-bubble {
  max-width: 80%;
  overflow: hidden;
  padding: 10px 16px;
  border-radius: 20px;
  position: relative;
  box-shadow: rgba(100, 100, 100, 0.1) 2px 3px 5px;
}
.message-item.human {
  display: flex;
  flex-direction: row-reverse;
}
.message-item.human .message-bubble {
  background: rgb(110, 177, 248);
  color: white;
  padding: 3px 16px 2px;
  margin-right: 10px;
}

.message-item.ai .message-bubble  {
  background: white;
  border: 1px solid #ebeef5;
}

/* 修复级联选择器的焦点问题 */
:deep(.el-cascader__dropdown) {
  z-index: 9999 !important;
}

:deep(.el-cascader-panel .el-radio) {
  display: none;
}

:deep(.el-cascader-node) {
  padding-left: 20px !important;
}

:deep(.el-cascader-node__label) {
  padding-left: 0 !important;
}
</style>